package org.chengyi.model_shop.service.impl;

import org.chengyi.model_shop.entity.*;
import org.chengyi.model_shop.mapper.CartMapper;
import org.chengyi.model_shop.mapper.OrderMapper;
import org.chengyi.model_shop.mapper.ProductMapper;
import org.chengyi.model_shop.mapper.UserMapper;
import org.chengyi.model_shop.service.OrderService;
import org.chengyi.model_shop.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;

    @Transactional
    public String addOrder(Order order) {
        Integer userId = ThreadLocalUtil.get();
        if (userId == null) {
            return "用户未登录";
        }
        User user = userMapper.getById(userId);
        if (user == null) {
            return "用户不存在";
        }

        // 1. 查询购物车所有商品
        List<Cart> cartList = cartMapper.getCartList(userId);

        // 2. 计算总金额
        double totalAmount = 0.0;
        for (Cart cart : cartList) {
            Double singlePrice = productMapper.getPriceById(cart.getProductId());
            totalAmount += singlePrice * cart.getQuantity();
        }
        order.setTotalAmount(totalAmount);

        order.setUserId(userId);
        order.setCreatedAt(new Date());
        order.setStatus(0);
        order.setAddress(user.getAddress());

        // 3. 下单时先扣减库存
        for (Cart cart : cartList) {
            int updateStock = productMapper.deleteProductStockById(cart.getProductId(), cart.getQuantity());
            if (updateStock == 0) {
                throw new RuntimeException("商品ID " + cart.getProductId() + " 库存不足，无法下单");
            }
        }

        // 4. 插入order表
        int result = orderMapper.addOrder(order);

        // 5. 插入order_item表
        for (Cart cart : cartList) {
            OrderItem item = new OrderItem();
            item.setOrderId(order.getId());
            item.setProductId(cart.getProductId());
            item.setQuantity(cart.getQuantity());
            Double singlePrice = productMapper.getPriceById(cart.getProductId());
            item.setPrice(singlePrice * cart.getQuantity());
            orderMapper.addOrderItem(item);
        }
        
        // 6. 清空用户购物车
        cartMapper.deleteAllCartByUserId(order.getUserId());
        
        return result > 0 ? "添加成功" : "添加失败";
    }

    @Override
    public List<OrderDetailDTO> selectOrderItmByUserId(Integer userId) {
        // 1. 基本校验：确保提供了 userId
        if (userId == null) {
            return Collections.emptyList();
        }

        // 2. 业务校验：检查用户是否存在
        // 这样可以防止为不存在的用户查询订单
        User user = userMapper.getById(userId);
        if (user == null) {
            return Collections.emptyList();
        }

        // 3. 从 Mapper 获取订单数据
        List<OrderDetailDTO> orders = orderMapper.selectOrderItmByUserId(userId);

        // 4. 确保方法从不返回 null 集合
        return orders != null ? orders : Collections.emptyList();
    }

    @Override
    public String shipOrder(Integer orderId) {
        if (orderId == null) {
            return "订单ID不能为空";
        }
        // 根据约定，状态 1 代表 "已发货"
        final int SHIPPED_STATUS = 1;
        int rowsAffected = orderMapper.updateOrderStatus(orderId, SHIPPED_STATUS);
        
        return rowsAffected > 0 ? "发货成功" : "订单不存在或更新失败";
    }

    @Override
    public List<AdminOrderDetailDTO> getAllAdminOrders() {
        return orderMapper.selectAllAdminOrders();
    }

    @Override
    public List<AdminOrderDetailDTO> getOrderListByUserName(String username) {
        return orderMapper.getOrderListByUserName(username);
    }
}
